package com.wyp.didishige.activity.near;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.wyp.didishige.activity.BaseActivity;
import com.wyp.didishige.activity.users.UserInfoActivity;
import com.wyp.didishige.adapter.NearPeopleAdapter;
import com.wyp.didishige.config.Config;
import com.wyp.didishige.model.UserModel;
import com.wyp.didishige.utils.CollectionUtils;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.wiget.xlist.XListView;
import com.wyp.didishige.R;
import com.wyp.didishige.model.User;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.CountListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SQLQueryListener;

/**
 * 附近的人列表
 *
 * @author smile
 * @ClassName: NewFriendActivity
 * @Description: TODO
 * @date 2014-6-6 下午4:28:09
 */
public class NearPeopleActivity extends BaseActivity implements XListView.IXListViewListener, OnItemClickListener {

    XListView mListView;
    NearPeopleAdapter adapter;
    private Boolean sex = false;
    List<User> nears = new ArrayList<User>();
    private int SIZE = 20;
    User user;
    private double QUERY_KILOMETERS = 100;//默认查询10公里范围内的人

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_near_people);
        user = BmobUser.getCurrentUser(this, User.class);
        initActionBar();
        initView();
    }

    private void initActionBar() {
        actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
        actionBar.setTitle("附近的人");
    }

    private void initView() {
        initXListView();
    }

    private void initXListView() {
        mListView = (XListView) findViewById(R.id.list_near);
        mListView.setOnItemClickListener(this);
        // 首先不允许加载更多
        mListView.setPullLoadEnable(false);
        // 允许下拉
        mListView.setPullRefreshEnable(true);
        // 设置监听器
        mListView.setXListViewListener(this);
        //
        mListView.pullRefreshing();

        adapter = new NearPeopleAdapter(this, nears);
        mListView.setAdapter(adapter);
        initNearByList(false);
    }


    int curPage = 0;
    ProgressDialog progress;

    private void initNearByList(final boolean isUpdate) {
        if (!isUpdate) {
            progress = new ProgressDialog(NearPeopleActivity.this);
            progress.setMessage("正在查询附近的人...");
            progress.setCanceledOnTouchOutside(true);
            progress.show();
        }

        if (user.getLocation().getLatitude() != 0 && user.getLocation().getLongitude() != 0) {
            queryMoreNearList(0);
        } else {
            ShowToast("暂无附近的人!");
            progress.dismiss();
            refreshPull();
        }

    }

    /**
     * 查询更多
     */
    private void queryMoreNearList(int page) {
        double latitude = user.getLocation().getLatitude();
        double longtitude = user.getLocation().getLongitude();
        BmobQuery<User> query = new BmobQuery<User>();
        String sql;
        if (sex!=null){
            sql = "select count(*) from _User where location near [" + longtitude + "," + latitude + "] max "
                    + QUERY_KILOMETERS + " km and sex = " + sex + " limit " + page * SIZE + " " + SIZE;
        }else{
            sql = "select count(*) from _User where location near [" + longtitude + "," + latitude + "] max "
                    + QUERY_KILOMETERS + " km limit " + page * SIZE + " " + SIZE;
        }
        query.doSQLQuery(this, sql, new SQLQueryListener<User>() {
            @Override
            public void done(BmobQueryResult<User> bmobQueryResult, BmobException e) {
                if (e == null) {
                    if (bmobQueryResult != null && bmobQueryResult.getResults() != null && bmobQueryResult.getResults().size() > nears.size()) {
                        adapter.addAll(bmobQueryResult.getResults());
                        refreshLoad();
                    } else {
                        ShowToast("数据加载完成");
                        mListView.setPullLoadEnable(false);
                        refreshLoad();
                    }
                } else {
                    ShowLog("查询更多附近的人出错");
                    mListView.setPullLoadEnable(false);
                    refreshLoad();
                }
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        User user = (User) adapter.getItem(position);
        Bundle bundle = new Bundle();

        bundle.putString(Config.KEY_USER_ID, user.getObjectId());
        IntentUtil.start_activity(NearPeopleActivity.this, UserInfoActivity.class, bundle);
    }

    @Override
    public void onRefresh() {
        initNearByList(true);
    }

    private void refreshLoad() {
        if (mListView.getPullLoading()) {
            mListView.stopLoadMore();
        }
    }

    private void refreshPull() {
        if (mListView.getPullRefreshing()) {
            mListView.stopRefresh();
        }
    }

    @Override
    public void onLoadMore() {
        double latitude = user.getLocation().getLatitude();
        double longtitude = user.getLocation().getLongitude();
        BmobQuery<User> query = new BmobQuery<User>();
        String sql;
        if (sex!=null){
            sql = "select count(*) from _User where location near [" + longtitude + "," + latitude + "] max "
                    + QUERY_KILOMETERS + " km and sex = " + sex ;
        }else{
            sql = "select count(*) from _User where location near [" + longtitude + "," + latitude + "] max "
                    + QUERY_KILOMETERS + " km";
        }
        query.doSQLQuery(this, sql, new SQLQueryListener<User>() {
            @Override
            public void done(BmobQueryResult<User> bmobQueryResult, BmobException e) {
                if (e == null) {
                    if (bmobQueryResult != null && bmobQueryResult.getResults() != null && bmobQueryResult.getResults().size() > nears.size()) {
                        curPage++;
                        queryMoreNearList(curPage);
                    } else {
                        ShowToast("数据加载完成");
                        mListView.setPullLoadEnable(false);
                        refreshLoad();
                    }
                } else {
                    ShowLog("查询附近的人总数失败");
                    refreshLoad();
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_nearpeople_activity, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        }
        if (id == R.id.action_all) {
            sex=null;
            onRefresh();
            return true;
        }

        if (id == R.id.action_female) {
            sex = false;
            onRefresh();
            return true;
        }
        if (id == R.id.action_male) {
            sex = true;
            onRefresh();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
